package site.jlopen.assets.spring;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;

import cn.hutool.core.io.resource.ResourceUtil;
import jakarta.annotation.PostConstruct;
import site.jlopen.components.entity.GraphNodeParam;
import site.jlopen.components.utils.ComponentsReaderUtils;
import site.jlopen.utils.StringUtil;

/**
* @ClassName: ComponentsInit
* @Description: 组件数据初始化
* @author ChenJiaLu
* @date 2025年2月10日 11:07:42
*
 */
@Component
public class ComponentsInit extends ComponentsReaderUtils {
	private final Logger logger = LoggerFactory.getLogger(getClass());
	@Value("${file.components}")
	private String fileComponents;
	
	@PostConstruct
    public void init() {
		String osName = System.getProperty("os.name").toLowerCase();
		logger.error("操作系统名称：{}", osName);
        if (osName.contains("win")) {
        	init2();
        }else {
        	File pfile = new File(fileComponents);
        	if(null == pfile || pfile.isDirectory() == false) {
        		logger.error("读取文件夹{}读取组件配置文件失败，该文件夹为空或者不是目录", fileComponents);
        	}
        	File[] files = pfile.listFiles();
        	if(null == files || files.length == 0) {
        		logger.error("读取文件夹{}读取组件配置文件失败，该文件夹不存在配置文件", fileComponents);
        	}
        	for (File file : files) {
        		try {
        			if(file.getPath().indexOf("secretflow") >= 0) {
						continue;
					}
					String content = Files.readString(Paths.get(file.getPath()), StandardCharsets.UTF_8);
					if(null != content && StringUtil.isNotBlank(content)) {
						GraphNodeParam jsonObj = JSON.parseObject(content, new TypeReference<GraphNodeParam>() {});
						if (null != jsonObj) {
							this.getParams().add(jsonObj);
						}
					}
				} catch (IOException e) {
					logger.error("读取文件{}异常: {}", file.getPath(), e);
					continue;
				}
			}
			for (GraphNodeParam param : this.getParams()) {
				this.getMaps().put(param.getCode(), param);
			}
        }
	}
    
	
    public void init2() {
		logger.info("开始初始化组件");
		List<URL>  componentRes = ResourceUtil.getResources("components");
		URL component = componentRes.get(0);
		try {
			String jsonfiles = ioStr(component.openStream());
			//logger.info("jsonfiles: {}", jsonfiles);
			String[] filenames = jsonfiles.split(".json");
			for (String filename : filenames) {
				if(null != filename && StringUtil.isNotBlank(filename)) {
					//String jsonText = ResourceUtil.readUtf8Str("components/"+filename+".json");
					if(filename.equals("secretflow")) {
						continue;
					}
					List<URL>  componentRess = ResourceUtil.getResources("components/"+filename+".json");
					URL components = componentRess.get(0);
					String jsonText = ioStr(components.openStream());
					logger.info("psiJsonText: {}", jsonText);
					try {
						if(null != jsonText && StringUtil.isNotBlank(jsonText)) {
							GraphNodeParam jsonObj = JSON.parseObject(jsonText, new TypeReference<GraphNodeParam>() {});
							if (null != jsonObj) {
								this.getParams().add(jsonObj);
							}
						}
					} catch (Exception e) {
						logger.error("读取文件{}异常: {}", filename, e);
						continue;
					}
				}
			}
			for (GraphNodeParam param : this.getParams()) {
				this.getMaps().put(param.getCode(), param);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		logger.info("组件初始化完成");
	}
	
	public void read_init() {
		try {
			List <URL> componentRes = ResourceUtil.getResources("components/");
			System.out.println("components size: " + componentRes.size());
			if(null != componentRes) {
				URL component = componentRes.get(1);
				System.out.println("component: " + component.getPath());
				//String jsonfiles = ioStr(component.openStream());
				String jsonfiles = ResourceUtil.readUtf8Str("components");
				System.out.println("jsonfiles text: " + jsonfiles);
				String[] filenames = jsonfiles.split(".json");
				for (String filename : filenames) {
					if(null != filename && StringUtil.isNotBlank(filename)) {
						String jsonText = ResourceUtil.readUtf8Str("components/" + filename + ".json");
						System.out.println("jsonText: " + jsonText);
						/*List<URL> resources = ResourceUtil.getResources("components/" + filename + ".json");
						URL resource = resources.get(0);
						System.out.println("jsonfiles text: " + jsoncontent);*/
						if(null != jsonText && StringUtil.isNotBlank(jsonText)) {
							GraphNodeParam jsonObj = JSON.parseObject(jsonText, new TypeReference<GraphNodeParam>() {});
							if (null != jsonObj) {
								this.getParams().add(jsonObj);
							}
						}
					}
				}
				for (GraphNodeParam param : this.getParams()) {
					this.getMaps().put(param.getCode(), param);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	

	
	@Bean
    public RestTemplate restTemplate() {
		RestTemplate restTemplate = new RestTemplate();
	    SimpleClientHttpRequestFactory simpleClientHttpRequestFactory = new SimpleClientHttpRequestFactory();
	    simpleClientHttpRequestFactory.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(3));
	    simpleClientHttpRequestFactory.setReadTimeout((int) TimeUnit.SECONDS.toMillis(5));
	    restTemplate.setRequestFactory(simpleClientHttpRequestFactory);
	    return restTemplate;
    }
}
